package com.atguigu.gmall.index.service;

import com.alibaba.fastjson.JSON;
import com.atguigu.gmall.common.bean.ResponseVo;
import com.atguigu.gmall.index.annotation.GmallCache;
import com.atguigu.gmall.index.feign.GmallPmsClient;
import com.atguigu.gmall.index.utils.DistributedLock;
import com.atguigu.gmall.pms.entity.CategoryEntity;
import org.apache.commons.lang3.StringUtils;
import org.bouncycastle.pqc.jcajce.provider.qtesla.SignatureSpi;
import org.redisson.api.RCountDownLatch;
import org.redisson.api.RLock;
import org.redisson.api.RReadWriteLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
public class IndexService {

    @Autowired
    private GmallPmsClient pmsClient;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private RedissonClient redissonClient;

    private static final String KEY_PREFIX = "index:cates:";
    private static final String LOCK_PREFIX = "index:category:lock:";

    @Autowired
    private DistributedLock distributedLock;

    public List<CategoryEntity> queryLvl1Categories() {
        ResponseVo<List<CategoryEntity>> categoryResponseVo = this.pmsClient.queryCategoriesByPid(0L);
        return categoryResponseVo.getData();
    }

    @GmallCache(prefix = KEY_PREFIX, timeout = 129600, random = 14400, lock = LOCK_PREFIX)
    public List<CategoryEntity> queryLvl2CategoriesWithSubs(Long cid) {
        System.out.println("=================3目标方法======================");
        ResponseVo<List<CategoryEntity>> categoryResponseVo = this.pmsClient.queryLvl23CategoriesWithSubs(cid);
        return categoryResponseVo.getData();
    }

    public List<CategoryEntity> queryLvl2CategoriesWithSubs2(Long cid) {
        // 1.先查询缓存，如果缓存中命中则直接返回
        String json = this.redisTemplate.opsForValue().get(KEY_PREFIX + cid);
        if (StringUtils.isNotBlank(json)) {
            return JSON.parseArray(json, CategoryEntity.class);
        }

        // 为了防止缓存击穿，添加分布式锁
        RLock fairLock = this.redissonClient.getFairLock(LOCK_PREFIX + cid);
        fairLock.lock();

        try {
            // 获取分布式锁的过程中，可能有其他请求已经获取过锁，并把数据放入缓存了。再次确认缓存是否存在需要的数据，如果有则直接返回
            String json2 = this.redisTemplate.opsForValue().get(KEY_PREFIX + cid);
            if (StringUtils.isNotBlank(json2)) {
                return JSON.parseArray(json2, CategoryEntity.class);
            }

            // 2.如果缓存没有命中，则查询数据库放入缓存
            ResponseVo<List<CategoryEntity>> categoryResponseVo = this.pmsClient.queryLvl23CategoriesWithSubs(cid);
            List<CategoryEntity> categoryEntities = categoryResponseVo.getData();
            if (CollectionUtils.isEmpty(categoryEntities)) {
                // 为了防止缓存穿透，数据即使为null也缓存，但是缓存时间不超过5min
                this.redisTemplate.opsForValue().set(KEY_PREFIX + cid, JSON.toJSONString(categoryEntities), 5, TimeUnit.MINUTES);
            } else {
                // 为了防止缓存雪崩，给缓存时间加随机值
                this.redisTemplate.opsForValue().set(KEY_PREFIX + cid, JSON.toJSONString(categoryEntities), 90 + new Random().nextInt(5), TimeUnit.DAYS);
            }
            return categoryEntities;
        } finally {
            fairLock.unlock();
        }
    }

    public void testLock() {
        RLock lock = this.redissonClient.getLock("lock");
        lock.lock();
        try {
            String json = this.redisTemplate.opsForValue().get("num");
            if (StringUtils.isBlank(json)) {
                this.redisTemplate.opsForValue().set("num", "1");
                return;
            }
            int num = Integer.parseInt(json);
            this.redisTemplate.opsForValue().set("num", String.valueOf(++num));
        } finally {
            lock.unlock();
        }
    }

    public void testLock3() {
        String uuid = UUID.randomUUID().toString();
        this.distributedLock.tryLock("lock", uuid, 30);
        try {
            String json = this.redisTemplate.opsForValue().get("num");
            if (StringUtils.isBlank(json)) {
                this.redisTemplate.opsForValue().set("num", "1");
                return;
            }
            int num = Integer.parseInt(json);
            this.redisTemplate.opsForValue().set("num", String.valueOf(++num));

            try {
                TimeUnit.SECONDS.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        } finally {
            this.distributedLock.unlock("lock", uuid);
        }
    }

    public void testSubLock(String uuid) {
        this.distributedLock.tryLock("lock", uuid, 30);
        System.out.println("======================");
        this.distributedLock.unlock("lock", uuid);
    }

    public void testLock2() {
        // 获取锁
        String uuid = UUID.randomUUID().toString();
        Boolean lock = this.redisTemplate.opsForValue().setIfAbsent("lock", uuid, 3, TimeUnit.SECONDS);
        if (!lock) {
            // 获取锁失败则进行重试
            try {
                Thread.sleep(50);
                this.testLock();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } else {
            try {
                // 给锁设置过期时间解决死锁问题
                //this.redisTemplate.expire("lock", 3, TimeUnit.SECONDS);
                String json = this.redisTemplate.opsForValue().get("num");
                if (StringUtils.isBlank(json)) {
                    this.redisTemplate.opsForValue().set("num", "1");
                    return;
                }
                int num = Integer.parseInt(json);
                this.redisTemplate.opsForValue().set("num", String.valueOf(++num));
            } finally {
                // 释放锁：先判断再释放
                String script = "if redis.call('get', KEYS[1]) == ARGV[1] " +
                        "then " +
                        "   return redis.call('del', KEYS[1]) " +
                        "else " +
                        "   return 0 " +
                        "end";
                this.redisTemplate.execute(new DefaultRedisScript<>(script, Boolean.class), Arrays.asList("lock"), uuid);
//                if (StringUtils.equals(uuid, this.redisTemplate.opsForValue().get("lock"))){
//                    this.redisTemplate.delete("lock");
//                }
            }
        }
    }

    public void testWrite() {
        RReadWriteLock rwLock = this.redissonClient.getReadWriteLock("rwLock");
        rwLock.writeLock().lock(10, TimeUnit.SECONDS);
        System.out.println("一顿操作。。。。");
        // rwLock.writeLock().unlock();
    }

    public void testRead() {
        RReadWriteLock rwLock = this.redissonClient.getReadWriteLock("rwLock");
        rwLock.readLock().lock(10, TimeUnit.SECONDS);
        System.out.println("一顿操作。。。。");
    }

    public void testLatch() {
        try {
            RCountDownLatch cdl = this.redissonClient.getCountDownLatch("cdl");
            cdl.trySetCount(6);
            cdl.await();
            System.out.println("班长一顿锁门操作。。。");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void testCountDown() {
        RCountDownLatch cdl = this.redissonClient.getCountDownLatch("cdl");
        System.out.println("同学出来了。。。");
        cdl.countDown();
    }

    public static void main(String[] args) {
        System.out.println(test());
    }

    private static int test(){
        try {
            int a = 5;
            System.out.println("==============");
            return a;
        } finally {
            return 4;
        }
    }
}
